`timescale 1ns/100ps
`default_nettype none

module Odd_Colour_Space_Conv(
	input logic CLOCK_50_I,
	input logic resetn,

	input logic [31:0] Y,
	input logic [31:0] U,
	input logic [31:0] V,
	input logic start,
	
	input logic [31:0] mulResult1,
	output logic [31:0] mul1_Op1,
	output logic [31:0] mul1_Op2,
	input logic [31:0] mulResult2,
	output logic [31:0] mul2_Op1,
	output logic [31:0] mul2_Op2,
	input logic [31:0] mulResult3,
	output logic [31:0] mul3_Op1,
	output logic [31:0] mul3_Op2,

	output logic [7:0] R,
	output logic [7:0] G,
	output logic [7:0] B,
	output logic finish
);

enum logic [2:0]{
	S0,
	S1
}state;

logic [31:0] acc1;
logic [31:0] acc2;
logic [31:0] acc3;

always_ff @ (posedge CLOCK_50_I or negedge resetn) begin
	if (resetn == 1'b0)begin
	   acc1 <= 32'b0;
	   acc2 <= 32'b0;
	   acc3 <= 32'b0;
	   finish <= 1'b0;
	   state <= S0;
	end else begin
	   case (state)
	   S0: begin
	       if (start) begin
	           acc1 <=  mulResult1 + mulResult3;
		       acc2 <=  mulResult1;
	           acc3 <=  mulResult1 + mulResult2;
	           finish <= 1'b0;
	           state <= S1;
	       end
	   end
	   S1: begin
	       acc2 <= acc2 - mulResult2 - mulResult3;
		   finish <= 1'b1;
		   state <= S0;
         end
	   default: state <= S0;
	   endcase
     end
end

always_comb begin
        case(state)
        S0: begin
            mul1_Op1 = 32'd76284;
            mul1_Op2 = Y-32'd16;
            mul2_Op1 = 32'd132251;
            mul2_Op2 = U-32'd128;
            mul3_Op1 = 32'd104595;
            mul3_Op2 = V-32'd128;
        end
        S1: begin
            mul1_Op1 = 32'b0;
            mul1_Op2 = 32'b0;
            mul2_Op1 = 32'd25624;
            mul2_Op2 = U-32'd128;
            mul3_Op1 = 32'd53281;
            mul3_Op2 = V-32'd128;
        end
        default: begin
            mul1_Op1 = 32'b0;
            mul1_Op2 = 32'b0;
            mul2_Op1 = 32'b0;
            mul2_Op2 = 32'b0;
            mul3_Op1 = 32'b0;
            mul3_Op2 = 32'b0;
        end
        endcase
end
//The worst case of RGB calculation result is a 12 bit number. But we chop it into 8 bit.  
assign R = (acc1[31]==1)?8'b0:(|acc1[30:24])?8'd255:acc1[23:16];
assign G = (acc2[31]==1)?8'b0:(|acc2[30:24])?8'd255:acc2[23:16];
assign B = (acc3[31]==1)?8'b0:(|acc3[30:24])?8'd255:acc3[23:16];

endmodule
        
